using Infrastructure.Attribute;
using Infrastructure.Extensions;
using System.Linq.Expressions;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Infrastructure.Filters;
using Mapster;
using ZR.Repository;
using ZR.Service.BaseFrame.IService;
using ZR.Model.BaseFrame.Dto;
using ZR.Model.BaseFrame.Entity;
using ZR.Model.Enums;

namespace ZR.Service.BaseFrame.Service
{

    /// <summary>
    /// 部门服务
    /// </summary>
    [AppService(ServiceType = typeof(IDepartService), ServiceLifetime = LifeTime.Scoped)]
    public class DepartService : DepartServiceBase, IDepartService
    {
        /// <summary>
        /// 获取组织树选择列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<List<TreeNodeInfo>> GetOrgDepartTreeSelectList(GetOrgDepartTreeSelectListReq req)
        {
            //var idPath = $"/{req.CompanyId}/";
            var companyListQuery = Repository.Context.Queryable<CompanyEntity>()
                .WhereIF(req.CompanyId > 0, m =>1==2)
                .Where(m => m.StateCode == DataStateEnum.Enabled.ToEnumCode())
                .Select(m => new TreeNodeInfo
                {
                    Id = m.CompanyId.ToString(),
                    PaId = m.PaCompanyId.ToString(),
                    Label = m.CompanyName,
                    Type=OrgTypeEnum.Company.ToEnumCode(),
                    IsDefaultNodeType = false
                });
            var departListQuery = Repository.Context.Queryable<DepartEntity>()
                .InnerJoin<CompanyEntity>((m, n) => m.CompanyId == n.CompanyId)
                .WhereIF(req.CompanyId > 0, (m, n) => m.CompanyId==req.CompanyId)
                .Where(m => m.StateCode == DataStateEnum.Enabled.ToEnumCode())
                .Select(m => new TreeNodeInfo
                {
                    Id = m.DepartId.ToString(),
                    PaId = SqlFunc.IF(m.PaDepartId > 0).Return(m.PaDepartId).End(m.CompanyId).ToString(),
                    Label = m.DepartName,
                    Type = OrgTypeEnum.Dept.ToEnumCode(),
                    IsDefaultNodeType = true
                });
            var list = await Repository.Context.UnionAll(companyListQuery, departListQuery)
                .ToListAsync();
            if (!(req.CompanyId > 0) && req.IsReturnRoot)
            {
                list.Add(new TreeNodeInfo
                {
                    Id = "0",
                    Label = string.IsNullOrWhiteSpace(req.RootNodeName) ? "所有组织" : req.RootNodeName,
                    PaId = "-1",
                    IsDefaultNodeType = false
                });
            }
            var treeList = BuildTree(list);
            return treeList;
        }
    }
}